package com.edu.mybatisIntercept;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.CachingExecutor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

/**
 * @作者 five-five
 * @创建时间 2021/1/13
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type=StatementHandler.class,method="parameterize",args={Statement.class})
})
public class MyTestExecutePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();//目标方法
//        System.out.println("目标对象：" + target);
        //这个方法是mybatis提供的，得到元数据,使用getValue()可以拿到getter和setter的值
        MetaObject metaObject = SystemMetaObject.forObject(target);
        BoundSql boundSql = (BoundSql) metaObject.getValue("boundSql");
//        System.out.println(boundSql.getSql());
        Object proceed = invocation.proceed();//拦截器放行
        return proceed;//返回的就是查询到的对象
    }

    @Override
    public Object plugin(Object target) {
        //target:核心对象
        //StatementHandler  ParameterHandler  ResultSetHandler   Executor
        //将拦截器中定义的增强功能和某一个核心对象合并起来,称为最终的核心对象
        Object wrap = Plugin.wrap(target, this);
        System.out.println(wrap);
        return wrap;
    }

    @Override
    public void setProperties(Properties properties) {
        // 属性值
        System.out.println(properties);
    }
}
